//
//  LZMapViewController.m
//  laziz_Consumer
//
//  Created by XMac on 16/11/3.
//  Copyright © 2016年 XBN. All rights reserved.
//

#import "LZMapViewController.h"
#import "Masonry.h"
#import "CustomAnnotationView.h"
#import "SMCalloutView.h"
#import "LZMapModel.h"
#import "LZMapLocationManager.h"
#import "LZAlertView.h"
#import "extobjc.h"
#import <MapKit/MapKit.h>

@import GoogleMaps;

@interface LZMapViewController ()<GMSMapViewDelegate>

@property(nonatomic , strong) SMCalloutView *calloutView;
@property(nonatomic , strong) UIView *emptyCalloutView;
@property (strong, nonatomic) UIButton *nav_left_back;

@end

@implementation LZMapViewController

-(instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.hidesBottomBarWhenPushed = YES;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.umLogPageViewName = @"地图页面";
    
    self.title = LZLocalizedString(@"restaurant_address", nil);
    
    [self configUI];
    
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

-(void)dealloc{
    DLog(@"dealloc");
}

#pragma
#pragma mark Private method

-(void)configUI{
    
    
    GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:self.restaurantModel.latitude longitude:self.restaurantModel.longitude zoom:6];
    
    GMSMapView *mapView = [GMSMapView mapWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), CGRectGetHeight(self.view.bounds)-64) camera:camera];
    
    mapView.delegate = self;
    
    mapView.myLocationEnabled = YES;
    
    [self.view addSubview:mapView];
    
    GMSMarker *marker = [GMSMarker new];
    marker.position = CLLocationCoordinate2DMake(self.restaurantModel.latitude, self.restaurantModel.longitude);
    marker.icon = [UIImage imageNamed:@"map_location_icon_select"];
    marker.map = mapView;
    
    
    
    /*
     ==========================================annotation=================================================
     */
    self.calloutView = [SMCalloutView new];
    
    CustomAnnotationView *annotationView = [[CustomAnnotationView alloc]initWithTitle:self.restaurantModel.title detail:self.restaurantModel.content];
    
    @weakify(self)
    [annotationView setNavigationBlock:^{
        @strongify(self)
        [self openAppleMapToNavigateOperation];
//        UIAlertController *alertSheet = [UIAlertController alertControllerWithTitle:LZLocalizedString(@"navigate", nil) message:LZLocalizedString(@"please_select_one_map", nil) preferredStyle:UIAlertControllerStyleActionSheet];
//        
//        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:LZLocalizedString(@"change_cancel", nil) style:UIAlertActionStyleCancel handler:nil];
//        
//        UIAlertAction *appleMapNavigateAction = [UIAlertAction actionWithTitle:LZLocalizedString(@"apple_map", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//            @strongify(self)
//            [self openAppleMapToNavigateOperation];
//        }];
//        
//        UIAlertAction *googleMapNavigateAction = [UIAlertAction actionWithTitle:LZLocalizedString(@"google_map", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//            @strongify(self)
//            [self openGoogleMapToNavigateOperation];
//        }];
//        
//        [alertSheet addAction:cancelAction];
//        [alertSheet addAction:appleMapNavigateAction];
//        [alertSheet addAction:googleMapNavigateAction];
//        
//        [self presentViewController:alertSheet animated:YES completion:nil];
    }];
    
    [annotationView sizeToFit];
    
    self.calloutView.contentView = annotationView;
    self.calloutView.contentViewInset = UIEdgeInsetsMake(0, 0, 0, 0);
    
    self.emptyCalloutView = [UIView new];
    
}




- (void)showAddressPermissionsAlert {
    LZAlertView *alert = [[LZAlertView alloc] initWithContent:LZLocalizedString(@"iphone_permissions_address_remind", nil) andImage:nil cancelButtonTitle:LZLocalizedString(@"cancel", nil) otherButtonTitles:LZLocalizedString(@"iphone_permissions_go_setting", nil),nil];
    [alert show];
    
    alert.clickButtonIndexBlock = ^(NSInteger index) {
        if (index == 1) {
            [[UIApplication sharedApplication]openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
        }
    };
}

- (void)showDownloadGoogleMapAppAlert {
    LZAlertView *alert = [[LZAlertView alloc] initWithContent:LZLocalizedString(@"iphone_download_google_map", nil) andImage:nil cancelButtonTitle:LZLocalizedString(@"cancel", nil) otherButtonTitles:LZLocalizedString(@"confirm", nil),nil];
    [alert show];
    
    alert.clickButtonIndexBlock = ^(NSInteger index) {
        if (index == 1) {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"https://itunes.apple.com/bh/app/google-maps-navigation-transport/id585027354?mt=8"]];
        }
    };
}

-(void)openAppleMapToNavigateOperation{
    if ([LZMapLocationManager shareLocationManager].isOpenLocation) {
        CLLocationCoordinate2D coordinate = {self.restaurantModel.latitude,self.restaurantModel.longitude};
//        CLLocationCoordinate2D coordinate = {39.542637,116.232922};
        MKMapItem *currentLocation = [MKMapItem mapItemForCurrentLocation];
        MKMapItem *toLocation = [[MKMapItem alloc] initWithPlacemark:[[MKPlacemark alloc] initWithCoordinate:coordinate addressDictionary:nil]];
        
        [MKMapItem openMapsWithItems:@[currentLocation, toLocation]
                       launchOptions:@{MKLaunchOptionsDirectionsModeKey: MKLaunchOptionsDirectionsModeDriving,
                                       MKLaunchOptionsShowsTrafficKey: @(YES)}];
    }else {
        // 如果没开定位
        [self showAddressPermissionsAlert];
    }
}

-(void)openGoogleMapToNavigateOperation{
    if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"comgooglemaps://"]]) {
        
        /**
         https://developers.google.com/maps/documentation/ios-sdk/urlscheme?hl=zh-cn  规则文档
         
         saddr：设置路线搜索的起点。 它可以是一个纬度、经度或查询格式的地址。 如果它是返回多个结果的查询字符串， 将选择第一个结果。 如果该值留空，那么将使用该用户的当前位置。
         daddr：设置路线搜索的终点。 具有与 saddr 相同的格式和行为。
         directionsmode：交通方式。 可以设置为：driving、transit、bicycling 或 walking。
         
         */
        
        if ([LZMapLocationManager shareLocationManager].isOpenLocation) {
            // 如果打开了定位,则更新一下定位信息
            if ([LZMapLocationManager shareLocationManager].currentLocation) {
                NSString *strUrl = [NSString stringWithFormat:@"comgooglemaps://?saddr=%f,%f&daddr=%f,%f&directionsmode=transit",[LZMapLocationManager shareLocationManager].currentLocation.coordinate.latitude,[LZMapLocationManager shareLocationManager].currentLocation.coordinate.longitude,self.restaurantModel.latitude,self.restaurantModel.longitude];
                
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:strUrl]];
            }
            else {
                [[LZMapLocationManager shareLocationManager] startLocationSuccess:^(CLLocation *aLocation, NSString *cityName) {
                    NSString *strUrl = [NSString stringWithFormat:@"comgooglemaps://?saddr=%f,%f&daddr=%f,%f&directionsmode=transit",[LZMapLocationManager shareLocationManager].currentLocation.coordinate.latitude,[LZMapLocationManager shareLocationManager].currentLocation.coordinate.longitude,self.restaurantModel.latitude,self.restaurantModel.longitude];
                    
                    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:strUrl]];
                } Failed:^(NSError *error) {
                    DLog(@"定位失败");
                }];
            }
        }
        else {
            // 如果没开定位
            [self showAddressPermissionsAlert];
        }
        
    } else {
        DLog(@"Can't use comgooglemaps://");
        [self showDownloadGoogleMapAppAlert];
    }
}

#pragma
#pragma mark GMSMapViewDelegate
-(UIView *)mapView:(GMSMapView *)mapView markerInfoWindow:(GMSMarker *)marker{
    
    CLLocationCoordinate2D anchor = marker.position;
    CGPoint point = [mapView.projection pointForCoordinate:anchor];
    
    self.calloutView.calloutOffset = CGPointMake(0, -25);
    self.calloutView.hidden = NO;
    
    CGRect calloutRect = CGRectZero;
    calloutRect.origin = point;
    calloutRect.size = CGSizeZero;
    
    [self.calloutView presentCalloutFromRect:calloutRect
                                      inView:mapView
                           constrainedToView:mapView
                                    animated:YES];
    
    return self.emptyCalloutView;
}


- (void)mapView:(GMSMapView *)pMapView didChangeCameraPosition:(GMSCameraPosition *)position {
    /* move callout with map drag */
    if (pMapView.selectedMarker != nil && !self.calloutView.hidden) {
        CLLocationCoordinate2D anchor = [pMapView.selectedMarker position];
        
        CGPoint arrowPt = self.calloutView.backgroundView.arrowPoint;
        
        CGPoint pt = [pMapView.projection pointForCoordinate:anchor];
        pt.x -= arrowPt.x;
        pt.y -= arrowPt.y + 25;
        
        self.calloutView.frame = (CGRect) {.origin = pt, .size = self.calloutView.frame.size };
    } else {
        self.calloutView.hidden = YES;
    }
}


- (void)mapView:(GMSMapView *)mapView didTapAtCoordinate:(CLLocationCoordinate2D)coordinate {
    self.calloutView.hidden = YES;
}

- (BOOL)mapView:(GMSMapView *)mapView didTapMarker:(GMSMarker *)marker {
    mapView.selectedMarker = marker;
    return YES;
}




@end
